﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Security.Permissions;
using WSIMServices.model;
using System.ServiceModel.Channels;

namespace WSIMServices
{
    // NOTE: If you change the class name "IWSIMGeneralOperations" here, you must also update the reference to "IWSIMGeneralOperations" in Web.config.
    public class WSIMGeneralOperations : IWSIMGeneralOperations
    {

        #region IWSIMGeneralOperations Members

        [OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
        [PrincipalPermission(SecurityAction.Demand, Role = "User")]
        public void UserLeave()
        {
            WSIMProfilesTableAdapters.wsim_online_usersTableAdapter online = new WSIMServices.WSIMProfilesTableAdapters.wsim_online_usersTableAdapter();
            WSIMProfilesTableAdapters.wsim_userTableAdapter users = new WSIMServices.WSIMProfilesTableAdapters.wsim_userTableAdapter();
            online.Delete((long)users.GetID(OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name));            
        }

        #endregion

        #region IWSIMGeneralOperations Members

        [OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
        [PrincipalPermission(SecurityAction.Demand, Role = "User")]
        public long IsValid()
        {
            WSIMProfilesTableAdapters.wsim_online_usersTableAdapter online = ObjectFactory.GetOnlineTable();
            WSIMProfilesTableAdapters.wsim_userTableAdapter users = ObjectFactory.GetUserTable();
            WSIMProfilesTableAdapters.wsim_user_access_detailTableAdapter access = ObjectFactory.GetUserAccessTable();

            OperationContext context = OperationContext.Current;
            MessageProperties properties = context.IncomingMessageProperties;
            RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

            
            long id=(long)users.GetID(OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name);
            access.Insert(endpoint.Address, DateTime.Now, id);
            online.Insert(id);
            return id;
        }

        #endregion
    }
}
